package com.geng.io.bio;

import java.io.*;
import java.net.Socket;

public class BIOServerHandler implements Runnable {
    private Socket socket;
    public BIOServerHandler(Socket socket){
        this.socket = socket;
    }

    @Override
    public void run() {
        BufferedWriter writer = null;
        BufferedReader reader = null;
        try{
            reader = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
            writer = new BufferedWriter(new OutputStreamWriter(this.socket.getOutputStream()));

            while(true){
                String line = reader.readLine();
                if(line == null){
                    break;
                }
                System.out.println(line);
                writer.write(line + "\n");
                writer.flush();
            }
        }catch (Exception e){
            if(reader != null){
                try{
                    reader.close();
                }catch (IOException e1){
                    e1.printStackTrace();
                }
            }
            if(socket != null){
                try{
                    socket.close();
                }catch (IOException e2){
                    e2.printStackTrace();
                }
            }
        }
    }
}
